import axios from 'axios';
import store from '../../store';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();

const service = axios.create({
  timeout: 1000 * 60,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  baseURL: process.env.NODE_ENV === 'development' ? '/apis' : process.env.VUE_APP_WEB_URL
});
console.log(window.location.href);
console.log(window.location.href.slice(-36));
service.interceptors.request.use(
  config => {
    let token = window.location.href.slice(-36);
    // let token = sessionStorage.getItem('TOKEN');
    if (token) {
      config.headers['Authorization'] = 'bearer ' + token;
    }
    store.commit('user/isLoading', true);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  res => {
    store.commit('user/isLoading', false);
    if (res.data.code === 200 || res.data.code === '200' || res.data.code === 500) {
      return res.data || res;
    } else if (res.data.code === 401 || res.data.code === 403) {
      // 未授权，请重新登录
    } else {
      return Promise.reject(res);
    }
    return res;
  },
  error => {
    console.log(error);
    store.commit('user/isLoading', false);
    switch (error.response.status) {
      case 400:
        error.message = '请求错误(400)';
        break;
      case 401:
        error.message = '未授权，请重新登录(401)';
        break;
      case 403:
        error.message = '拒绝访问(403)';
        break;
      case 404:
        error.message = '请求出错(404)';
        break;
      case 408:
        error.message = '请求超时(408)';
        break;
      case 500:
        error.message = '服务器错误(500)';
        break;
      case 501:
        error.message = '服务未实现(501)';
        break;
      case 502:
        error.message = '网络错误(502)';
        break;
      case 503:
        error.message = '服务不可用(503)';
        break;
      case 504:
        error.message = '网络超时(504)';
        break;
      case 505:
        error.message = 'HTTP版本不受支持(505)';
        break;
      default:
        error.message = '未知错误';
    }
    return Promise.reject(error);
  }
);

export default service;
